<template>
	<view class="content" @touchstart='touchstart' @touchend='touchend' @touchmove='touchmove'>
		<navbar title='消息列表' :avatar="userInfo.avatar">
			<view class="addFriend" @tap='openMenu' slot='opBtn'>
				<image src="/static/icon/navbar/add_friend.png" mode=""></image>
			</view>
		</navbar>
		<scroll-view scroll-y="true" :refresher-enabled='true' :enable-back-to-top='true' :refresher-threshold='150'
			refresher-default-style='black' :refresher-triggered='triggered' @refresherrefresh="onRefresh"
			@refresherrestore="onRestore" @refresherabort="onAbort" refresher-background="rgba(128,128,128,.1)"
			style="height:calc(100vh - 250rpx);padding-bottom: 200rpx;border: 1px solid;">
			<search ref='search'></search>
			<view class="list-wrap">
				<view class="list-item" @tap="toChat(item,index)" v-for="(item,index) in listGroup" :key='index'>
					<view class="avatar">
						<image :src="avatarArray[index].avatar" mode=""></image>
					</view>
					<view class="nick-msg">
						<view class="nick">{{avatarArray[index].nickName || item.from.sender}}</view>
						<view class="msg">{{item.msg}}</view>
					</view>
					<view class="time-nums">
						<view class="time">{{item.date | parseTime}}</view>
						<view class="nums">
							<view v-show="item.msgNum > 0">
								<uni-badge :text="text" type="success" size="small" :inverted="true"
									style="background-color: red;color: #FFFFFF;"></uni-badge>
							</view>
						</view>
					</view>
				</view>
				<view style="color:rgba(127,127,127,.8);text-align: center;margin-top: 400rpx;">暂时没有消息，快去找好友聊天吧~</view>
			</view>

		</scroll-view>
		<u-toast ref="uToast" />
		<u-action-sheet :list="list" v-model="show" @click="oplistclick"></u-action-sheet>
	</view>
</template>

<script>
	import search from "@/components/search.vue"
	import mySelf from "@/components/my_self.vue"
	import {
		mapState,
		mapMutations
	} from 'vuex'
	export default {
		components: {
			search,
			mySelf
		},

		data() {
			return {
				text: 99,
				triggered: true,
				_freshing: false,
				show: false,
				title: 'Hello',
				listGroup: [],
				list: [{
					text: '添加好友'
				}, {
					text: '扫一扫'
				}],
				touchS: {},
				currentPage: '',
				current: 1,
				disableTouch: true,
				chatObj: {},
				avatarArray: []


			}
		},
		computed: {
			...mapState(['userInfo'])
		},
		onNavigationBarButtonTap(e) {
			console.log(e)
			//侧滑打开页面
			if (e.key == 'self') {
				this.$refs.my_self.open()
			} else {
				this.show = true
			}

		},
		filters: {
			parseTime(val) {
				let date = new Date(parseInt(val))
				let currentDate = new Date().getDate()
				if (date.getDate() === currentDate) {
					return `${date.getHours() > 12 ?'下午 ':'上午 '}${date.getHours()}:${date.getMinutes() < 10 ?'0'+date.getMinutes():date.getMinutes()}`
				} else {
					return `${date.getFullYear()}-${date.getMonth()+1}-${date.getDate()}`
				}

			}
		},
		mounted() {
			this.reloadData()
			uni.$on('PRIVATE_MSG_SYSTEM_USER', data => {
				console.log('INDEX页面接收私有消息', data)
				//查询数据库 
				// #ifdef APP-PLUS
				this.$selectSql({
					name: 'chat',
					sql: `select * from "${data.from.sender}"`
				}).then(res => {
					// console.log(res)
					// console.log(res.data[res.data.length - 1])
					// console.log(this.listGroup)
					if (this.listGroup.length == 0) {
						res.data[res.data.length - 1].from = JSON.parse(res.data[res.data.length - 1].from)
						this.listGroup.unshift(res.data[res.data.length - 1])
					} else {
						this.listGroup.forEach((ele, index) => {
							console.log(ele)
							if (ele.from.sender === data.from.sender) {
								console.log('发送者相同')
								res.data[res.data.length - 1].from = JSON.parse(res.data[res.data
									.length - 1].from)
								this.$set(this.listGroup, index, res.data[res.data.length - 1])

							}
						})
						console.log(this.listGroup)
					}

				})
				// #endif
			})
			uni.$on('changeAvatar', res => {
				this.userInfo.avatar = res
			})
		},

		methods: {
			reloadData() {
				this.listGroup = []
				// #ifdef APP-PLUS
				this.$opChatDB.queryAllTable().then(res => {
					console.log(res)
					if (res.code === 1) {
						//数据库中的所有表
						let allTable = res.data
						//遍历表，获取数据 
						allTable.forEach(ele => {
							if (ele.name != 'android_metadata') {
								console.log('不是默认表')
								//查询此表的最后一条数据
								this.$opChatDB.queryLastOne(ele.name).then(res => {
									console.log(`表${ele.name}的最后一条数据`, res)
									res.data[0].from = JSON.parse(res.data[0].from)
									res.data[0].from.sender = ele.name
									this.listGroup.unshift(res.data[0])
									//获取头像 
									this.listGroup.forEach(ele => {
										this.$api.getTargetAvatar(
												`?user=${ele.from.sender}`)
											.then(res => {
												console.log('获取的头像', res)
												this.avatarArray.push(res.data.data[
													0] || {})
												console.log(this.avatarArray[0])
											})
									})
								})
							}
						})
					}
				})

				// #endif
			},
			onAbort() {
				console.log("onAbort");
				this.triggered = false
				this._freshing = false
			},
			onRestore() {
				// this.triggered = 'restore'; // 需要重置
				console.log("onRestore");
			},
			onRefresh(e) {
				console.log(e)
				if (this._freshing) return;
				if (!this.triggered) {
					this.triggered = true
					this._freshing = true
				}
				//模拟获取数据
				setTimeout(() => {
					this.triggered = false
					this._freshing = false
				}, 2000)
			},
			changeAvatar(e) {
				this.avatar = e
			},
			openMenu() {
				this.show = true
			},
			swiperChange(e) {
				this.current = e.detail.current
			},
			changCurrent() {
				this.current = 0
			},
			touchstart(e) {
				this.touchS = e.changedTouches[0]
			},
			touchmove(e) {
				//计算y轴浮动差
				let diffY = e.changedTouches[0].clientY - this.touchS.clientY
				let diffX = e.changedTouches[0].clientX - this.touchS.clientX
				if (Math.abs(diffY) < 25 && Math.abs(diffX) > 40) {
					//判断滑动方向
					//1 结束时x 大于 开始是x 向右
					if (Math.abs(e.changedTouches[0].clientX) > Math.abs(this.touchS.clientX)) {
						this.current = 0
					}
					if (Math.abs(e.changedTouches[0].clientX) < Math.abs(this.touchS.clientX)) {
						this.current = 1
					}
				}
			},
			touchend(e) {},
			oplistclick(index) {
				switch (index) {
					case 0:
						console.log('添加好友')
						this.$refs.search.openSearch({
							type: 'add_friend',
							placeholder: '添加好友'
						})
						break;
					case 1:
						let cmr = plus.camera.getCamera()
						var res = cmr.supportedImageResolutions[0];
						var fmt = cmr.supportedImageFormats[0];
						cmr.captureImage(function(path) {
								alert("Capture image success: " + path);
							},
							function(error) {
								alert("Capture image failed: " + error.message);
							}, {
								resolution: res,
								format: fmt
							}
						);
				}
			},
			back() {
				uni.navigateTo({
					url: '../login/login'
				})
			},
			toChat(item, index) {
				console.log(item)
				let obj = {
					flag: 'index',
					index: index
				}

				uni.navigateTo({
					url: `../privateChatRoom/privateChatRoom?receiverId=${item.from.senderId}&receiver=${item.from.sender}&nickName=${this.avatarArray[index].nickName}&avatar=${this.avatarArray[index].avatar}`,
					fail: (err) => {
						console.log(err)
					}
				})
			}
		}
	}
</script>

<style lang="scss" scoped>
	.addFriend {
		width: 50rpx;
		height: 50rpx;
		position: absolute;
		right: 15rpx;
		bottom: 10rpx;

		/*  */
		image {
			width: 100%;
			height: 100%;
		}

	}

	.content {
		height: 100vh;
		// border: 1px solid red;
		// background-color: set-text-color(yellow);
		background-color: $themnBgColor;
	}

	.list-wrap {
		.list-item {
			height: 120rpx;
			background: #FFFFFF;
			margin: 10rpx 0;
			display: flex;
			align-items: center;
			padding: 0 20rpx;

			.avatar {
				width: 80rpx;
				height: 80rpx;
				border-radius: 50%;
				// border: 1px solid;
				overflow: hidden;
				line-height: 120rpx;

				image {
					width: 100%;
					height: 100%;
				}
			}

			.nick-msg {
				width: 500rpx;
				margin-left: 20rpx;

				// border: 1px solid;
				.nick {
					font-size: 32rpx;

				}

				.msg {
					color: #909399;
					font-size: 24rpx;
					margin: 10rpx 0;
				}
			}

			.time-nums {
				font-size: 24rpx;
				height: 80rpx;

				.time {}

				.nums {
					text-align: center;
					margin-top: 10rpx;
					// border: 1px solid;
					display: flex;
					justify-content: center;
					align-items: center;

					view {
						// display: inline-block;
						// border: 1px solid;
						border-radius: 50%;
						display: flex;
						justify-content: center;
						align-items: center;
						width: 40rpx;
						height: 40rpx;
						background: #FA3534;
						color: #FFFFFF;
						transform: scale(.8);

					}

				}
			}

		}
	}

	@function set-text-color($color) {
		@if(lightness($color) > 70) {
			@return #333
		}
	}
</style>
